package com.baoxian.workschedule.mapper

import com.baoxian.workschedule.model.*
import org.apache.commons.lang.StringUtils
import org.apache.log4j.Logger

/**
 * User: ZhengCongChun
 * Date: 13-7-12
 * Time: 下午2:56
 * @Version 1.0
 *      To change this template use File | Settings | File Templates.
 */
class TaskWorkScheduleXmlLoader {
    private static final Logger log = Logger.getLogger(TaskWorkScheduleXmlLoader.class)
    //配置文件路径
    private String configFilePath
    //全局默认配置信息
    private GlobalWorkDayTimeModel globalWorkDayTimeConfig = null//new GlobalWorkDayTimeModel()
    //具体机构处理任务的配置信息
    private LinkedHashMap organizationConfig = null//new LinkedHashMap()

    private long fileModifiedTime

    /**
     * TaskWorkScheduleXmlLoader,装载配置文件
     * @param configureFilePath 配置文件路径
     */
    void init(String configureFilePath) {
        if (log.debugEnabled) log.debug("==== Start the initialization of TaskWorkScheduleXmlLoader: init(); The configureFilePath: ${configureFilePath} ====")

        if (StringUtils.isNotBlank(configureFilePath)) {
            configFilePath = configureFilePath
        } else {
            configFilePath = this.getClass()?.getResourceAsStream('baoxian-task-workschedule.xml')?.file
        }
        if (!loadConfiguration()) {
            throw new IllegalArgumentException("==== Error: An Exception occurred while Loading configuration file: TaskWorkScheduleXmlLoader.init() ====")
        }

        if (log.debugEnabled) log.debug("==== Initialization Success. The globalWorkDayTimeConfig: ${globalWorkDayTimeConfig}; The organizationConfig: ${organizationConfig} ====")
    }

    /**
     * 装载配置信息
     * @return
     */
    private boolean loadConfiguration() {
        boolean result = true
        try {
            log.debug("==== TaskWorkScheduleXmlLoader.loadConfiguration() ====")
            File configFile = new File(configFilePath)

            fileModifiedTime = configFile?.lastModified()

            def scheduleFieldMapping = new XmlParser().parseText(configFile.getText('utf-8'))

            globalWorkDayTimeConfig = loadGlobalWorkDayTimeConfigMapping(scheduleFieldMapping)

            organizationConfig = loadOrganizationConfigMapping(scheduleFieldMapping)

        } catch (Exception e) {
            log.error("==== An error occurred while loading the configuration information ====", e)
            result = false
        }
        return result
    }

    /**                                                            0
     * 装载全局配置信息
     * @param globalWorkDayTimeMapping
     */
    private GlobalWorkDayTimeModel loadGlobalWorkDayTimeConfigMapping(Node taskWorkScheduleMapping) {
        GlobalWorkDayTimeModel globalWorkDayTimeConfig = new GlobalWorkDayTimeModel()
        List<CommonDayTimeModel> holidayModelList = new ArrayList<CommonDayTimeModel>()
        log.debug("==== 循环读取globalWorkdDayTime中的属性值，解析 baoxian-task-workschedule.xml文件中 globalWorkDayTime 标签的属性 ====")
        //解析globalWorkDayTime.holiday
        taskWorkScheduleMapping?.globalWorkDayTime?.holiday?.each {
            CommonDayTimeModel model = new CommonDayTimeModel()
            model?.startDate = it?.startDate?.text()
            model?.endDate = it?.endDate?.text()
            model?.startTime = it?.startTime?.text()
            model?.endTime = it?.endTime?.text()
            holidayModelList.add(model)
        }
        globalWorkDayTimeConfig?.holiday = holidayModelList

        //解析globalWorkDayTime.weekWorkDay
        List<WeekWorkDayModel> weekWorkDay = new ArrayList<WeekWorkDayModel>()
        taskWorkScheduleMapping?.globalWorkDayTime?.weekWorkDay?.each {
            WeekWorkDayModel model = new WeekWorkDayModel()
            model?.startDay = Integer.valueOf(it?.weekStartDay?.text() ?: "0")
            model?.endDay = Integer.valueOf(it?.weekEndDay?.text() ?: "0")
            model?.startTime = it?.startTime?.text()
            model?.endTime = it?.endTime?.text()
            weekWorkDay.add(model)
        }
        globalWorkDayTimeConfig?.weekWorkDay = weekWorkDay

        //解析globalWorkDayTime.workTime
        BaseTimeModel workTime = new BaseTimeModel()
        workTime?.startTime = taskWorkScheduleMapping?.globalWorkDayTime?.workTime?.startTime?.text()
        workTime?.endTime = taskWorkScheduleMapping?.globalWorkDayTime?.workTime?.endTime?.text()
        globalWorkDayTimeConfig?.workTime = workTime

        //解析其他全局默认信息
        globalWorkDayTimeConfig?.preProcessTime = Integer.valueOf(taskWorkScheduleMapping?.globalWorkDayTime?.preProcessTime?.text() ?: "0")
        globalWorkDayTimeConfig?.forbiddenMessage = taskWorkScheduleMapping?.globalWorkDayTime?.forbiddenMessage?.text()
        globalWorkDayTimeConfig?.tipMessage = taskWorkScheduleMapping?.globalWorkDayTime?.tipMessage?.text()
        globalWorkDayTimeConfig?.actionFlags = taskWorkScheduleMapping?.globalWorkDayTime?.actionFlags?.text()

        return globalWorkDayTimeConfig
        log.debug("==== Finished Load GlobalWorkScheduleConfigMapping!!! ====")
    }

    /**
     * 装载Organization配置信息
     * @param organizationMapping
     */
    private Map loadOrganizationConfigMapping(Node taskWorkScheduleMapping) {
        Map organizationConfig = new LinkedHashMap()
        log.debug("==== 循环读取organizations中的 organization属性，解析 baoxian-task-workschedule.xml 文件中 organization 标签的属性")
        //循环加载organization
        taskWorkScheduleMapping?.organizations?.organization?.each { Node orgNode ->
            LinkedHashMap<String, Object> organizationMap = new LinkedHashMap<String, Object>()
            //循环加载organization.task
            orgNode?.task?.each { Node taskNode ->
                TaskModel taskModel = new TaskModel()
                WorkDayTimeModel workDayTimeModel = new WorkDayTimeModel()
                //解析WorkTime
                BaseTimeModel workTime = new BaseTimeModel()
                String stime = taskNode?.workDayTime?.workTime?.startTime?.text()?.toString()
                if (stime?.length() < 8) {
                    stime = stime + ":00"
                }
                workTime?.startTime = stime

                String etime = taskNode?.workDayTime?.workTime?.endTime?.text()?.toString()
                if (etime?.length() < 8) {
                    etime = etime + ":00"
                }
                workTime?.endTime = etime

                workDayTimeModel?.workTime = workTime
                //解析organizations.organization.task.workDayTime.weekWorkDay
                List<WeekWorkDayModel> weekWorkDayModelList = new ArrayList<WeekWorkDayModel>()
                taskNode?.workDayTime?.weekWorkDay?.each {
                    WeekWorkDayModel model = new WeekWorkDayModel()
                    model?.startDay = Integer.valueOf(it?.weekStartDay?.text() ?: "0")
                    model?.endDay = Integer.valueOf(it?.weekEndDay?.text() ?: "0")
                    String modelStime = it?.startTime?.text()?.toString()
                    if (modelStime?.length() < 8) {
                        modelStime = modelStime + ":00"
                    }
                    model?.startTime = modelStime

                    String modelEtime = it?.endTime?.text()?.toString()
                    if (modelEtime?.length() < 8) {
                        modelEtime = modelEtime + ":00"
                    }
                    model?.endTime = modelEtime

                    weekWorkDayModelList?.add(model)
                }
                workDayTimeModel?.weekWorkDay = weekWorkDayModelList

                //解析organizations.organization.task.workDayTime.specialWorkDayTime
                List<CommonDayTimeModel> specialWorkDayTime = new ArrayList<CommonDayTimeModel>()
                taskNode?.workDayTime?.specialWorkDayTime?.each {
                    CommonDayTimeModel model = new CommonDayTimeModel()
                    model?.startDate = it?.startDate?.text()
                    model?.endDate = it?.endDate?.text()
                    String modelStime = it?.startTime?.text()?.toString()
                    if (modelStime?.length() < 8) {
                        modelStime = modelStime + ":00"
                    }
                    model?.startTime = modelStime

                    String modelEtime = it?.endTime?.text()?.toString()
                    if (modelEtime?.length() < 8) {
                        modelEtime = modelEtime + ":00"
                    }
                    model?.endTime = modelEtime

                    specialWorkDayTime?.add(model)
                }
                workDayTimeModel?.specialWorkDayTime = specialWorkDayTime

                //解析organizations.organization.task.workDayTime.specialHoliday
                List<CommonDayTimeModel> specialHoliday = new ArrayList<CommonDayTimeModel>()
                taskNode?.workDayTime?.specialHoliday?.each {
                    CommonDayTimeModel model = new CommonDayTimeModel()
                    model?.startDate = it?.startDate?.text()
                    model?.endDate = it?.endDate?.text()
                    String modelStime = it?.startTime?.text()?.toString()
                    if (modelStime?.length() < 8) {
                        modelStime = modelStime + ":00"
                    }
                    model?.startTime = modelStime

                    String modelEtime = it?.endTime?.text()?.toString()
                    if (modelEtime?.length() < 8) {
                        modelEtime = modelEtime + ":00"
                    }
                    model?.endTime = modelEtime

                    specialHoliday?.add(model)
                }
                workDayTimeModel?.specialHoliday = specialHoliday

                //解析organizations.organization.task.workDayTime.specialWeekWorkDay
                List<WeekWorkDayModel> specialWeekWorkday = new ArrayList<WeekWorkDayModel>()
                taskNode?.workDayTime?.specialWeekWorkday?.each {
                    WeekWorkDayModel model = new WeekWorkDayModel()
                    model?.startDay = Integer.valueOf(it?.weekStartDay?.text() ?: "0")
                    model?.endDay = Integer.valueOf(it?.weekEndDay?.text() ?: "0")
                    String modelStime = it?.startTime?.text()?.toString()
                    if (modelStime?.length() < 8) {
                        modelStime = modelStime + ":00"
                    }
                    model?.startTime = modelStime

                    String modelEtime = it?.endTime?.text()?.toString()
                    if (modelEtime?.length() < 8) {
                        modelEtime = modelEtime + ":00"
                    }
                    model?.endTime = modelEtime

                    specialWeekWorkday?.add(model)
                }
                workDayTimeModel?.specialWeekWorkDay = specialWeekWorkday

                taskModel?.workDayTime = workDayTimeModel

                taskModel?.preProcessTime = Integer.valueOf(taskNode?.preProcessTime?.text() ?: "0")
                taskModel?.actionFlag = taskNode?.actionFlag?.text()
                taskModel?.tipMessage = taskNode?.tipMessage?.text()
                taskModel?.taskType = taskNode?.attribute("type")?.toString()

                organizationMap?.put(taskNode?.attribute("type")?.toString(), taskModel)
            }
            organizationConfig?.put(orgNode?.attribute("id").toString(), organizationMap)
        }

        return organizationConfig
    }

    /**
     * 重新加载加载XML内容到内存
     * @return
     */
    boolean refreshConfigInfo() {
        if (globalWorkDayTimeConfig != null) {
            globalWorkDayTimeConfig = null
        }
        if (organizationConfig != null) {
            organizationConfig = null
        }

        return loadConfiguration()
    }
}
